package com.zuohuaipan.headine.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.tencent.connect.UserInfo;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.zuohuaipan.headine.MainActivity;
import com.zuohuaipan.headine.R;
import com.zuohuaipan.lazyviewpager_master.LazyFragmentPagerAdapter;
import com.zuohuaipan.lazyviewpager_master.LazyViewPager;
import com.zuohuaipan.pagerslidingtabstrip.PagerSlidingTabStrip;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by ASUS on 2017/1/4.
 */


public class Home_Fragment extends Fragment implements View.OnClickListener {
    public LazyViewPager vp;
    public PagerSlidingTabStrip ps;
    private MainActivity activity;
    public SlidingMenu menu;
    private TextView logo;
    private RelativeLayout login_phone;
    private RelativeLayout login_weixin;
    private RelativeLayout login_qq;
    private ImageView login_xx;
    private AlertDialog dialog;
    private Tencent mTencent;
    private String App_ID = "1105924500";
    private IUiListener loginListener;
    private IUiListener userInfoListener;
    private IUiListener shareInfoListener;
    //获取权限列表。所有权限为 all
    private static String SCOPE = "all";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceStte) {
        View view = inflater.inflate(R.layout.home_layout, null);
        activity = (MainActivity) getActivity();
        //初始化
        initView(view);
        //监听
        setListener();
        return view;
    }

    private void setListener() {
        logo.setOnClickListener(this);
    }


    private void initView(View view) {

        vp = (LazyViewPager) view.findViewById(R.id.vp);
        ps = (PagerSlidingTabStrip) view.findViewById(R.id.ps);
        logo = (TextView) view.findViewById(R.id.logo);

        //设置适配器
        vp.setAdapter(new MyAdapter(getChildFragmentManager()));
        //绑定,实现联动
        ps.setViewPager(vp);
        ps.setTextSize(50);
        ps.setIndicatorColor(Color.RED);
        ps.setIndicatorHeight(4);
        ps.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {


            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                activity.getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        //初始化登录
        initQqLogin();

    }

    /**
     * 判断是否登录
     */
    public void showdialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        dialog = builder.create();
        //找到视图
        View view = View.inflate(getActivity(), R.layout.login_dialog, null);
        //找到控件
        initdialogView(view);
        //监听
        setonListener();
        dialog.setView(view);
        dialog.show();


    }

    private void setonListener() {
        login_phone.setOnClickListener(this);
        login_weixin.setOnClickListener(this);
        login_qq.setOnClickListener(this);
        login_xx.setOnClickListener(this);
    }

    private void initdialogView(View view) {
        login_phone = (RelativeLayout) view.findViewById(R.id.login_phone);
        login_weixin = (RelativeLayout) view.findViewById(R.id.login_weixin);
        login_qq = (RelativeLayout) view.findViewById(R.id.login_qq);
        login_xx = (ImageView) view.findViewById(R.id.login_XX);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_phone:
                break;
            case R.id.login_weixin:
                break;
            case R.id.login_qq:
//                Toast.makeText(getActivity(), "点击了", Toast.LENGTH_SHORT).show();
                mTencent.login(this, SCOPE, loginListener);
                break;
            case R.id.login_XX:
                dialog.dismiss();
                break;
            case R.id.logo:
                islogin();
                break;
        }
    }

    //初始化QQ登录分享的需要的资源
    private void initQqLogin() {
        try {
            mTencent = Tencent.createInstance(App_ID, getActivity());
        } catch (Exception e) {
            e.printStackTrace();
        }

        //创建QQ登录回调接口
        loginListener = new IUiListener() {
            @Override
            public void onComplete(Object o) {
                dialog.dismiss();

                //登录成功后回调该方法
                Toast.makeText(getActivity(), "登录成功", Toast.LENGTH_SHORT).show();
                SharedPreferences spf = getActivity().getSharedPreferences("myheading", Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = spf.edit();
                edit.putBoolean("islogin", true);
                edit.commit();


                //设置openid，如果不设置这一步的话无法获取用户信息
                JSONObject jo = (JSONObject) o;
                String openID;
                try {
                    openID = jo.getString("openid");
                    String accessToken = jo.getString("access_token");
                    String expires = jo.getString("expires_in");
                    mTencent.setOpenId(openID);
                    mTencent.setAccessToken(accessToken, expires);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(UiError uiError) {
                //登录失败后回调该方法
                Toast.makeText(getActivity(), "登录失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel() {
                //取消登录后回调该方法
                Toast.makeText(getActivity(), "取消登录", Toast.LENGTH_SHORT).show();
            }
        };
        //获取用户信息的回调接口
        userInfoListener = new IUiListener() {
            @Override
            public void onComplete(Object o) {
                JSONObject jo = (JSONObject) o;
                try {
                    JSONObject info = (JSONObject) o;
                    //获取用户具体信息
                    String nickName = info.getString("nickname");
                    String figureurl_qq_2 = info.getString("figureurl_qq_2");
                    SharedPreferences sp = getActivity().getSharedPreferences("myheading", Context.MODE_PRIVATE);
                    SharedPreferences.Editor edit1 = sp.edit();
                    edit1.putString("qqname", nickName);
                    edit1.putString("qqimg", figureurl_qq_2);
                    edit1.commit();


                    //开启事务
                    getActivity().getSupportFragmentManager()
                            .beginTransaction()
                            .replace(R.id.menu_fr, Menu_Fragment.newInstance("", ""))
                            .commit();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(UiError uiError) {

            }

            @Override
            public void onCancel() {

            }
        };
    }

    //获取用户信息
    private void getUserInfo() {
        UserInfo info = new UserInfo(getActivity(), mTencent.getQQToken());
        info.getUserInfo(userInfoListener);
    }

    //QQ登陆回调
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        //判断登陆成功

        //QQ登陆回调
        // Tencent.onActivityResultData(requestCode, resultCode, data, loginListener);
        //一定要加上，不然监听不起作用
        Tencent.handleResultData(data, loginListener);
        //获取用户信息
        getUserInfo();


    }








    private void showmenu() {
        logo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activity.getSlidingMenu().toggle(true);
            }
        });
    }

    public void islogin() {
        SharedPreferences spf = getActivity().getSharedPreferences("myheading", Context.MODE_PRIVATE);
        boolean b = spf.getBoolean("islogin", false);
        if (b) {

            //开启事务
            getActivity().getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.menu_fr, Menu_Fragment.newInstance("", ""))
                    .commit();
            showmenu();
        } else {
            showdialog();
        }
    }
    //创建适配器 继承lazyfragmentpageradapter
    class MyAdapter extends LazyFragmentPagerAdapter {
        private final String[] TITLES = {"推荐", "热点", "笑话", "社会", "手机", "娱乐",
                "情感", "电影", "科技", "汽车", "体育", "财经", "军事", "游戏"};

        String[] type = new String[]{"list", "headline", "list", "list",
                "list", "list", "list",
                "list", "list", "list", "list", "list", "list", "list"};
        String[] typeid = new String[]{"T1370583240249", "T1348647909107", "T1350383429665", "T1348648037603", "T1348649654285", "T1348648517839", "T1348650839000", "T1348648650048",
                "T1348649580692", "T1348654060988", "T1348649079062", "T1348648756099", "T1348648141035", "T1348654151579"};

        /**
         * 必须重写构造器
         *
         * @param fm
         */
        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        /**
         * 必须实现
         *
         * @param position
         * @return
         */
        @Override
        public CharSequence getPageTitle(int position) {
            return TITLES[position];
        }

        @Override
        protected Fragment getItem(ViewGroup container, int position) {
            return NewsFragment.newInstance(type[position], typeid[position]);
        }

        @Override
        public int getCount() {
            return TITLES.length;
        }
    }

}
